﻿using AutoMapper;
using MediatR;
using T.S.BaseData.Api.AppClinet.Commend.Cultivationinfo;
using T.S.BaseData.Domain.Entity;
using T.S.BaseData.ErrorCode;
using T.S.BaseData.Infrastructure.Base;

namespace T.S.BaseData.Api.AppClinet.CommendHand.Cultivationinfo
{
    public class HealthUpdCommandHandle : IRequestHandler<HealthUpdCommand, ApiResult<int>>
    {

        private readonly IBaseRepository<Health> healReppo;
        private readonly IMapper mapper;
        private readonly ILogger<HealthUpdCommandHandle> logger;

        public HealthUpdCommandHandle(IBaseRepository<Health> healReppo, 
            IMapper mapper, 
            ILogger<HealthUpdCommandHandle> logger)
        {
            this.healReppo = healReppo;
            this.mapper = mapper;
            this.logger = logger;
        }
        
        public Task<ApiResult<int>> Handle(HealthUpdCommand request, CancellationToken cancellationToken)
        {
            ApiResult<int> result = new ApiResult<int>();

            var heal = healReppo.GetAll().Where(x => x.Id == request.Id).FirstOrDefault();
            if (heal==null)
            {
                var model = mapper.Map<Health>(request);
                var r = healReppo.Crate(model);
                if (r>0)
                {
                    result.Code = ApiEnums.Success;
                    result.Data = r;
                    result.Meg = "添加成功";

                    logger.LogInformation("添加成功");
                }
                else
                {
                    result.Code = ApiEnums.Error;
                    result.Data = r;
                    result.Meg = "添加失败";

                    logger.LogInformation("添加失败");
                }
            }
            else
            {
                heal.HealthDays = request.HealthDays;
                heal.HealthMethod = request.HealthMethod;
                heal.HealthWay = request.HealthWay;

                var r = healReppo.Update(heal);
                if (r > 0)
                {
                    result.Code = ApiEnums.Success;
                    result.Data = r;
                    result.Meg = "更新成功";

                    logger.LogInformation("更新成功");
                }
                else
                {
                    result.Code = ApiEnums.Error;
                    result.Data = r;
                    result.Meg = "更新失败";

                    logger.LogInformation("更新失败");
                }
            }

            return Task.FromResult(result);

        }

    }
}
